<template>
    <view class="container">
        <view class="content">
            <view class="list">
                <view class="item" @tap="tapitem(i)" :style="{marginTop:i.top?i.top:'1rpx'}" v-for="i in config" :key="i.key">
                    <view class="view">{{i.title}}</view>
                    <view>
                        <view class="text"
                              v-if="localData[i.key] !== null && localData[i.key] !== undefined"
                              :style="{ color: getStatusColor(i.key, localData[i.key]) }">
                            {{formatDataValue(i.key, localData[i.key])}}
                        </view>
                        <view class="text" v-else :style="{ color: '#07C160' }">空</view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    import request from "@/util/request";

    export default {
        name: "currentData",
        props: {
            config: {
                type: Array,
                default: () => [
                    { title: '设备识别码', key: 'equipmentId' },
                    { title: '数据发送时间', key: 'sendTime' },
                    { title: '设备类型', key: 'deviceType' },
                    // 监控数据字段
                    { title: '产品ID', key: 'productId' },
                    { title: 'CSQ', key: 'csq' },
                    { title: '系统告警', key: 'alarm' },
                    { title: '告警数据', key: 'alarmsDat' },
                    { title: '传感器数据', key: 'sensorDat' },
                    { title: '设备类型', key: 'devType' },
                    { title: '数据采样时间', key: 'sampTime' },
                    { title: '电量百分比', key: 'batLevel' },
                ]
            },
            data: {
                type: Object,
                default: () => ({})
            }
        },
        data() {
            return {
                localData: {}
            };
        },
        onLoad(options) {
            console.log(options.equipmentId)
            this.equipmentInputStoreId = options.id;
            this.warnTime = options.warnTime;
            this.localData.equipmentId = options.equipmentId;
            this.fetchRealtimeData();
        },
        methods: {
            // 获取状态对应的颜色
            getStatusColor(key, value) {
                // 报警状态字段（值为1时报警）
                const alarmKeys = [
                    'alarm', 'alarmsDat'
                ];

                // 故障状态字段（值为1时故障）
                const faultKeys = [];

                // 特殊状态字段
                const specialKeys = {
                    // 'ctrlCommStatus': value => value === 0 ? '#FF0000' : '#07C160' // 0=异常(红)，1=正常(绿)
                };

                // 检查特殊字段
                if (specialKeys[key]) {
                    return specialKeys[key](value);
                }

                // 报警字段处理
                if (alarmKeys.includes(key)) {
                    if (key === "alarm") {
                        return value === 1 ? '#FF0000' : '#07C160';
                    }
                }

                // 故障字段处理
                if (faultKeys.includes(key)) {
                    return value === 1 ? '#999999' : '#07C160';
                }

                // 默认正常状态（绿色）
                return '#07C160';
            },
            // 格式化数据显示
            formatDataValue(key, value) {
                if (key === 'alarm') {
                    return value === 1 ? '报警' : '正常';
                }
                if (key === 'batLevel') {
                    return value + "%"
                }
                return value;
            },

            // 从后端接口获取实时数据
            async fetchRealtimeData() {
                try {
                    let response = await request.get("/warn-fire-cock/getInfo?equipmentInputStoreId=" + this.equipmentInputStoreId + "&warnTime=" + this.warnTime);
                    if (response.data) {
                        console.log('获取实时数据成功:', response.data);
                        this.parseRealtimeData(response.data);
                    }
                } catch (error) {
                    console.error('获取实时数据失败:', error);
                }
            },

            // 解析实时数据到当前组件
            parseRealtimeData(data) {
                // 同时更新到列表数据
                Object.keys(data).forEach(key => {
                    this.$set(this.localData, key, data[key]);
                });
            },

            getUrl(url){
                if(!url){
                    return null;
                }

                const urlResult = {type: "String", data: ""};
                if(url.includes(',')){
                    const urlList = url.split(',');
                    return {
                        type: "Array",
                        data: urlList
                    };
                }

                return {
                    type: "String",
                    data: url
                };
            },

            tapitem(info) {
                console.log('点击项:', info);
            }
        }
    }
</script>

<style lang="scss" scoped>
    @import url("@/common/globleCSS/photoPreview.css");
    .container {
        height: 100%;
        padding-bottom: constant(safe-area-inset-bottom);
        /* 适配iOS<11.2 */
        padding-bottom: env(safe-area-inset-bottom);
        /* 适配iOS>11.2 */
    }

    .content {
        height: 100%;
        /* 假设底部吸底栏高度为50px */
        overflow-y: auto;
        /* 开启滚动 */
    }

    .list {
        display: flex;
        flex-direction: column;
        background-color: #f2f2f2;
    }

    .item {
        display: flex;
        align-items: center;
        background-color: #fff;
        justify-content: space-between;
        flex-wrap: wrap;
        padding: 0 30rpx;

        &:active {
            background-color: #f2f2f2;
        }

        .view {
            padding: 30rpx 0;
            font-size: 14px;
            flex: 1;
            color: #333333;
        }

        .text {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 0;
            overflow: hidden;
            font-size: 14px;
            color: #999;
        }
    }
</style>
